// 验证邮箱方法引入
const emailFn = require('../dao/emailServe')
const { numFn } = require('../model/Numcode')
    // redis引入
const redisClient = require('../redis/index')
    // 统一返回前端方法
const { sendFn, querySql, intercept } = require('../model/send')
    // 密码加密、解密方法
const { encryption, verifcation } = require('../dao/bcrypt')
    // token方法
const { generateToken, verifyToken } = require('../dao/jwt')
const io = require('../socket/index')
const { promise } = require('../config/db')
    // 字符串下划线转驼峰
const formatToHump = item => {
    let resObj = {}
    let KEYS = ''
    for (let KEY in item) {
        KEYS = KEY.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())

        resObj[KEYS] = item[KEY]
    }
    return resObj
}
let Keys = null
const LoginMethod = {
    login: async(req, res) => {
        let { userInfo, password } = req.body
        console.log(encryption(password))
        password = String(password)
        const resp = await querySql(res, 'SELECT * FROM user')
        if (resp[0].type !== 1) return sendFn(res, 500, '账号已封存，请联系管理员')
        if (!userInfo || !password) return sendFn(res, 500, '请填写账号密码')

        if (userInfo.length < 5 || password.length > 8) return sendFn(res, 500, '账号密码长度错误')
            // 判断数据库账号密码
        const obj = await resp.find(item => item.username == userInfo)
        if (!obj) return sendFn(res, 500, '账号不存在')
        const token = await generateToken(obj.userid)
        const passShow = await verifcation(password, obj.password)
        delete obj.password
        const data = { token, userInfo: obj }
        passShow ? sendFn(res, 200, '登陆成功', data) : sendFn(res, 500, '密码错误')
    },
    // 验证邮箱
    VerifyMailbox: (req, res) => {
        console.log(req.body.userInfo)
        let userInfo = req.body.userInfo
        db.query('SELECT * FROM user', async(err, er) => {
            if (err) return send(res, 500, '服务器错误' + err)
            const some = er.some(item => item.user_email == userInfo)
            if (!some) {
                // 随机验证码
                const num = numFn()
                    /* 增 改*/
                Keys = num
                setTimeout(() => {
                        Keys = null
                    }, 60000)
                    // await redisClient.set('key', num) // 设置值
                    // redisClient.expire('key', 60); //60秒自动过期
                    // 发送邮箱
                emailFn(userInfo, res, num)
            } else {
                send(res, 300, '该邮箱已绑定已存在')
            }
        })
    },
    // 注册
    Register: async(req, res) => {
        let { userInfo, password, nickName, verifynum } = req.body
        console.log(req.body)
            // 加密密码
        password = encryption(password)
        if (!userInfo || !password || !nickName) return res.send({ code: 401, msg: '请填写账号密码和昵称' })
            // const value = await redisClient.get('key') // 得到value 没有则为null
        if (verifynum.toLowerCase() != Keys || Keys == null || Keys == undefined)
            return res.send({ code: 300, msg: '验证码无效，请重新发送' })

        db.query('SELECT * FROM user ', (err, er) => {
            if (err) return send(res, 500, 'serveError' + err)

            index = er.some(item => item.user_email == userInfo)
            if (!index) {
                //插入数据
                db.query(
                    'insert into user(user_email,user_passwored,user_name,user_age,user_gender,user_personalizedsignature,user_mobilephonenumber,user_img) value(?,?,?,?,?,?,?,?)', [
                        userInfo,
                        password,
                        nickName,
                        '未填写',
                        '未填写',
                        '未填写',
                        '未填写',
                        'https://guitar-img-1307419551.cos.ap-nanjing.myqcloud.com/1.jpg'
                    ]
                )
                send(res, 200, '注册成功')
            } else {
                send(res, 300, '该账号已存在')
            }
        })
    },
    // 获取个人信息
    GetUserInfo: async(req, res) => {
        const userInfo = await querySql(
            res,
            `SELECT * FROM user where userid=${req.query.id ? req.query.id : req.id}`,
            true
        )
        const role = await querySql(res, `SELECT * FROM role where role_id in(${userInfo[0].roleId.split(',')})`, true)
        console.log(role)
        const roleIds = role.map(item => item.roleId)
        const roleNames = role.map(item => item.roleName)
        userInfo[0].roleId = roleIds
        userInfo[0].roleName = roleNames
        sendFn(res, 200, '获取成功', userInfo[0])
    },

    // 修改主题色
    reviseTheme: async(req, res) => {
        console.log(req.body.color)
        if (intercept(req, res)) return
        console.log(req.body.id)
        const resp = await querySql(res, `UPDATE  user SET theme='${req.body.color}' WHERE userid= ${req.id}`)
        if (resp) sendFn(res, 200, '修改主题色成功')
    },
    queryTheme: async(req, res) => {
        if (!req.query.id) return sendFn(res, 1000, '请登录再操作哦')
        const id = toString(req.body.id)
        if (!id.length) return sendFn(res, 1000)
        const resp = await querySql(res, `SELECT  * FROM user  WHERE userid= ${req.id}`)
        sendFn(res, 200, '获取主题色成功', { theme: resp[0].theme, ui_theme: resp[0].ui_theme })
    },

    // 获取路由
    getRouter: async(req, res) => {
        const resp = await querySql(res, `SELECT  * FROM user  WHERE userid= ${req.id}`)
            // 查询角色 id 绑定的路由信息
        const roleRes = await querySql(res, `SELECT  * FROM authority WHERE role_id in (${resp[0].role_id})`, true)
        routerIds = roleRes.map(item => item.routerId).join(',')
        console.log(roleRes)

        // 路由表查询
        const routesRes = await querySql(res, `SELECT  * FROM router where id in(${routerIds})`)

        let routerArr = []
        routesRes.forEach(item => {
            // item = formatToHump(item)
            routerArr.push(formatToHump(item))
        })
        let routes = routerArr

        const muenList = [{
                keepAlive: '1',
                title: '项目',
                icon: 'icon-xiangmu',
                children: [{
                        title: '项目列表',
                        path: '/home/project'
                    },
                    {
                        title: '项目图表',
                        path: '/home/eatch'
                    }
                ]
            },
            {
                title: '吉他',
                icon: 'icon-jita',
                children: [
                    // 弹唱
                    {
                        title: '弹唱',
                        path: '/Guitar/sing'
                    },
                    // 指弹
                    {
                        title: '指弹',
                        path: '/Guitar/fingers'
                    }
                ]
            },
            {
                title: '业余',
                icon: 'icon-three-dimensional',
                children: [{
                    title: 'Three展示',
                    path: '/home/Three'
                }]
            }
        ]

        sendFn(res, 200, '路由获取成功', { routes })
    }
}

module.exports = LoginMethod